const { HealthRecord, FamilyMember } = require('../models');
const { Op } = require('sequelize');
const moment = require('moment');

// 获取健康记录列表
exports.getRecords = async (req, res) => {
  try {
    const userId = req.user.id;
    
    // 修复：接收member_id或memberId作为参数
    const { member_id, memberId, type, startDate, endDate, limit = 20, offset = 0 } = req.query;
    
    // 优先使用member_id，否则使用memberId
    const memberIdParam = member_id || memberId;
    
    // 构建查询条件
    const where = {};
    
    // 只能查询自己家庭成员的记录
    const memberIds = await FamilyMember.findAll({
      where: { user_id: userId },
      attributes: ['id']
    }).then(members => members.map(m => m.id));
    
    where.member_id = { [Op.in]: memberIds };
    
    // 根据家庭成员ID筛选
    if (memberIdParam) {
      where.member_id = memberIdParam;
    }
    
    // 根据记录类型筛选
    if (type) {
      where.type = type;
    }
    
    // 根据日期范围筛选
    if (startDate && endDate) {
      where.record_time = {
        [Op.between]: [
          moment(startDate).startOf('day').toDate(),
          moment(endDate).endOf('day').toDate()
        ]
      };
    } else if (startDate) {
      where.record_time = {
        [Op.gte]: moment(startDate).startOf('day').toDate()
      };
    } else if (endDate) {
      where.record_time = {
        [Op.lte]: moment(endDate).endOf('day').toDate()
      };
    }
    
    // 查询记录
    const records = await HealthRecord.findAndCountAll({
      where,
      include: [
        {
          model: FamilyMember,
          as: 'member',
          attributes: ['id', 'name', 'avatar']
        }
      ],
      order: [['record_time', 'DESC']],
      limit: parseInt(limit),
      offset: parseInt(offset)
    });
    
    return res.json({
      success: true,
      data: {
        records: records.rows,
        total: records.count,
        limit: parseInt(limit),
        offset: parseInt(offset)
      }
    });
  } catch (error) {
    console.error('获取健康记录列表错误:', error);
    return res.status(500).json({
      success: false,
      message: '服务器错误'
    });
  }
};

// 获取单个健康记录详情
exports.getRecordById = async (req, res) => {
  try {
    const userId = req.user.id;
    const recordId = req.params.id;
    
    // 只能查询自己家庭成员的记录
    const memberIds = await FamilyMember.findAll({
      where: { user_id: userId },
      attributes: ['id']
    }).then(members => members.map(m => m.id));
    
    const record = await HealthRecord.findOne({
      where: {
        id: recordId,
        member_id: { [Op.in]: memberIds }
      },
      include: [
        {
          model: FamilyMember,
          as: 'member',
          attributes: ['id', 'name', 'avatar']
        }
      ]
    });
    
    if (!record) {
      return res.status(404).json({
        success: false,
        message: '健康记录不存在'
      });
    }
    
    return res.json({
      success: true,
      data: { record }
    });
  } catch (error) {
    console.error('获取健康记录详情错误:', error);
    return res.status(500).json({
      success: false,
      message: '服务器错误'
    });
  }
};

// 创建健康记录
exports.createRecord = async (req, res) => {
  try {
    const userId = req.user.id;
    const { member_id, type, type_id, value, unit, record_time, note } = req.body;
    
    // 验证必要字段
    if (!member_id || !type || !value || !record_time) {
      return res.status(400).json({
        success: false,
        message: '缺少必要参数'
      });
    }
    
    // 验证成员是否属于当前用户
    const member = await FamilyMember.findOne({
      where: {
        id: member_id,
        user_id: userId
      }
    });
    
    if (!member) {
      return res.status(403).json({
        success: false,
        message: '无权为此成员添加记录'
      });
    }
    
    // 创建记录
    const newRecord = await HealthRecord.create({
      member_id,
      type,
      type_id,
      value,
      unit,
      record_time: moment(record_time).toDate(),
      note
    });
    
    return res.status(201).json({
      success: true,
      data: { record: newRecord },
      message: '健康记录创建成功'
    });
  } catch (error) {
    console.error('创建健康记录错误:', error);
    return res.status(500).json({
      success: false,
      message: '服务器错误'
    });
  }
};

// 更新健康记录
exports.updateRecord = async (req, res) => {
  try {
    const userId = req.user.id;
    const recordId = req.params.id;
    const updateData = req.body;
    
    // 验证记录是否存在且属于当前用户的家庭成员
    const memberIds = await FamilyMember.findAll({
      where: { user_id: userId },
      attributes: ['id']
    }).then(members => members.map(m => m.id));
    
    const record = await HealthRecord.findOne({
      where: {
        id: recordId,
        member_id: { [Op.in]: memberIds }
      }
    });
    
    if (!record) {
      return res.status(404).json({
        success: false,
        message: '健康记录不存在或无权限'
      });
    }
    
    // 如果要更改成员ID，需要验证新成员是否属于当前用户
    if (updateData.member_id && updateData.member_id !== record.member_id) {
      const newMember = await FamilyMember.findOne({
        where: {
          id: updateData.member_id,
          user_id: userId
        }
      });
      
      if (!newMember) {
        return res.status(403).json({
          success: false,
          message: '无权为此成员修改记录'
        });
      }
    }
    
    // 如果有记录时间，转换为Date对象
    if (updateData.record_time) {
      updateData.record_time = moment(updateData.record_time).toDate();
    }
    
    // 更新记录
    await record.update(updateData);
    
    return res.json({
      success: true,
      data: { record },
      message: '健康记录更新成功'
    });
  } catch (error) {
    console.error('更新健康记录错误:', error);
    return res.status(500).json({
      success: false,
      message: '服务器错误'
    });
  }
};

// 删除健康记录
exports.deleteRecord = async (req, res) => {
  try {
    const userId = req.user.id;
    const recordId = req.params.id;
    
    // 验证记录是否存在且属于当前用户的家庭成员
    const memberIds = await FamilyMember.findAll({
      where: { user_id: userId },
      attributes: ['id']
    }).then(members => members.map(m => m.id));
    
    const record = await HealthRecord.findOne({
      where: {
        id: recordId,
        member_id: { [Op.in]: memberIds }
      }
    });
    
    if (!record) {
      return res.status(404).json({
        success: false,
        message: '健康记录不存在或无权限'
      });
    }
    
    // 删除记录
    await record.destroy();
    
    return res.json({
      success: true,
      message: '健康记录删除成功'
    });
  } catch (error) {
    console.error('删除健康记录错误:', error);
    return res.status(500).json({
      success: false,
      message: '服务器错误'
    });
  }
}; 